<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="fragments/layout :: layout(~{::title}, ~{::section})">

<head>
    <title>图书列表 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>图书列表</h2>
            <a href="/book/add" class="btn btn-primary">
                <i class="fas fa-plus"></i> 添加图书
            </a>
        </div>

        <!-- 搜索表单 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">搜索条件</h5>
            </div>
            <div class="card-body">
                <form id="searchForm">
                    <div class="form-row">
                        <div class="form-group col-md-3">
                            <label for="name">图书名称</label>
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="author">作者</label>
                            <input type="text" class="form-control" id="author" name="author">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="isbn">ISBN</label>
                            <input type="text" class="form-control" id="isbn" name="isbn">
                        </div>
                        <div class="form-group col-md-3">
                            <label for="categoryId">分类</label>
                            <select class="form-control" id="categoryId" name="categoryId">
                                <option value="">全部</option>
                                <option th:each="category : ${categories}" th:value="${category.id}"
                                    th:text="${category.name}">分类名称</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-3">
                            <label for="status">状态</label>
                            <select class="form-control" id="status" name="status">
                                <option value="">全部</option>
                                <option value="1">上架</option>
                                <option value="0">下架</option>
                            </select>
                        </div>
                        <div class="form-group col-md-3">
                            <label for="publisher">出版社</label>
                            <input type="text" class="form-control" id="publisher" name="publisher">
                        </div>
                        <div class="form-group col-md-6 d-flex align-items-end">
                            <button type="button" id="searchBtn" class="btn btn-primary mr-2">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" id="resetBtn" class="btn btn-secondary">
                                <i class="fas fa-redo"></i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 调试信息 -->
        <div class="alert alert-info" id="debugInfo" style="display:none;">
            <pre id="debugContent"></pre>
        </div>

        <!-- 图书列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">图书列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>封面</th>
                                <th>名称</th>
                                <th>作者</th>
                                <th>ISBN</th>
                                <th>分类</th>
                                <th>库存</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="bookList">
                            <!-- 图书数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页将通过AJAX加载 -->
                    </ul>
                </nav>
            </div>
        </div>

        <script th:inline="javascript">
            $(document).ready(function () {
                // 定义全局变量
                let currentPage = 1;
                let pageSize = 10;

                // 页面加载时获取数据
                loadData();

                // 搜索按钮点击事件
                $('#searchBtn').click(function () {
                    currentPage = 1;
                    loadData();
                });

                // 重置按钮点击事件
                $('#resetBtn').click(function () {
                    $('#searchForm')[0].reset();
                    currentPage = 1;
                    loadData();
                });

                // 加载数据函数
                function loadData() {
                    // 获取表单数据
                    const formData = {
                        name: $('#name').val(),
                        author: $('#author').val(),
                        isbn: $('#isbn').val(),
                        categoryId: $('#categoryId').val(),
                        status: $('#status').val(),
                        publisher: $('#publisher').val(),
                        pageNum: currentPage,
                        pageSize: pageSize
                    };

                    // 显示加载中提示
                    $('#bookList').html('<tr><td colspan="9" class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></td></tr>');

                    // 发送AJAX请求
                    $.ajax({
                        url: '/book/api/list',
                        type: 'GET',
                        data: formData,
                        dataType: 'json',
                        success: function (res) {
                            console.log('API响应:', res);

                            // 不显示调试信息
                            // $('#debugContent').text(JSON.stringify(res, null, 2));
                            // $('#debugInfo').show();

                            if (res && res.code === 200) {
                                renderTable(res.data);
                                renderPagination(res.data);
                            } else {
                                let errorMsg = res ? res.message : '未知错误';
                                $('#bookList').html('<tr><td colspan="9" class="text-center text-danger">获取数据失败：' + errorMsg + '</td></tr>');
                                $('#pagination').html('');
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX错误:', status, error);
                            $('#bookList').html('<tr><td colspan="9" class="text-center text-danger">服务器错误，请稍后再试！</td></tr>');
                            $('#pagination').html('');

                            // 只在出错时显示调试信息
                            $('#debugContent').text('错误状态: ' + status + '\n错误信息: ' + error + '\n响应文本: ' + xhr.responseText);
                            $('#debugInfo').show();
                        }
                    });
                }

                // 渲染表格数据
                function renderTable(data) {
                    if (!data || !data.list) {
                        $('#bookList').html('<tr><td colspan="9" class="text-center">数据格式错误</td></tr>');
                        return;
                    }

                    const list = data.list;
                    let html = '';

                    if (list && list.length > 0) {
                        for (let i = 0; i < list.length; i++) {
                            const book = list[i];
                            html += `
                                <tr>
                                    <td>${book.id}</td>
                                    <td>
                                        <img src="${book.coverImage || '/images/default-book.jpg'}" 
                                             alt="${book.name}" 
                                             style="width: 50px; height: 70px;">
                                    </td>
                                    <td>${book.name}</td>
                                    <td>${book.author}</td>
                                    <td>${book.isbn}</td>
                                    <td>${book.categoryName || '未分类'}</td>
                                    <td>${book.stock}</td>
                                    <td>
                                        <span class="badge ${book.status === 1 ? 'badge-success' : 'badge-danger'}">
                                            ${book.status === 1 ? '上架' : '下架'}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="/book/detail/${book.id}" class="btn btn-info">
                                                <i class="fas fa-eye"></i> 详情
                                            </a>
                                            <a href="/book/edit/${book.id}" class="btn btn-primary">
                                                <i class="fas fa-edit"></i> 编辑
                                            </a>
                                            <button type="button" class="btn btn-danger" onclick="deleteBook(${book.id})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            `;
                        }
                    } else {
                        html = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
                    }

                    $('#bookList').html(html);
                }

                // 渲染分页
                function renderPagination(data) {
                    if (!data || typeof data.total === 'undefined') {
                        $('#pagination').html('');
                        return;
                    }

                    const total = data.total;
                    const totalPages = Math.ceil(total / pageSize);
                    let html = '';

                    // 上一页
                    html += `
                        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage - 1})">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                    `;

                    // 页码
                    for (let i = 1; i <= totalPages; i++) {
                        html += `
                            <li class="page-item ${currentPage === i ? 'active' : ''}">
                                <a class="page-link" href="javascript:void(0);" onclick="changePage(${i})">${i}</a>
                            </li>
                        `;
                    }

                    // 下一页
                    html += `
                        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage + 1})">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    `;

                    $('#pagination').html(html);
                }
            });

            // 切换页码
            function changePage(page) {
                if (page < 1) page = 1;
                window.currentPage = page;
                window.loadData();
            }

            // 删除图书
            function deleteBook(id) {
                if (confirm('确定要删除这本图书吗？')) {
                    $.ajax({
                        url: '/book/api/delete/' + id,
                        type: 'DELETE',
                        success: function (res) {
                            if (res.code === 200) {
                                alert('删除成功！');
                                window.loadData();
                            } else {
                                alert('删除失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }
            }
        </script>
    </section>
</body>

</html>